<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable />
            </el-form-item>
            <el-form-item label="任务类型" prop="taskType">
              <el-select v-model="queryParams.taskTypeId" placeholder="请选择任务类型" clearable>
                <el-option v-for="item in taskOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户类型">
              <el-select v-model="queryParams.userType" placeholder="请选择" clearable>
                <el-option v-for="dict in user_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="处理人" prop="handlerUserId">
              <user-input v-model="queryParams.handlerUserId" v-model:name="queryParams.handlerUserName" placeholder="请选择处理人"></user-input>
            </el-form-item>
            <el-form-item label="任务状态" prop="status">
              <el-select v-model="queryParams.status" clearable placeholder="请选择">
                <el-option v-for="dict in task_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="异议状态" prop="status">
              <el-select v-model="queryParams.objectionStatus" clearable placeholder="请选择">
                <el-option v-for="dict in task_objection_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="isVisible" label="预计开始时间" prop="expectedStartTime">
              <el-date-picker
                v-model="queryParams.expectedStartTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预计开始时间"
              />
            </el-form-item>
            <el-form-item v-if="isVisible" label="预计结束时间" prop="expectedEndTime">
              <el-date-picker
                v-model="queryParams.expectedEndTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预计结束时间"
              />
            </el-form-item>
            <el-form-item v-if="isVisible" label="实际开始时间" prop="actualStartTime">
              <el-date-picker
                v-model="queryParams.actualStartTime"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择实际开始时间"
              />
            </el-form-item>
            <el-form-item v-if="isVisible" label="实际结束时间" prop="actualEndTime">
              <el-date-picker v-model="queryParams.actualEndTime" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择实际结束时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" @click="isVisible = !isVisible">{{ isVisible ? '收起' : '展开' }}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务编码" align="center" prop="taskId" width="175" />
        <el-table-column label="任务名称" align="center" prop="taskName" width="150" show-overflow-tooltip />
        <el-table-column label="任务类型" align="center" prop="taskTypeName" width="100" />
        <el-table-column label="用户类型" align="center" prop="userType" width="100">
          <template #default="scope">{{ user_type.find((item) => item.value === scope.row.userType)?.label }}</template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="handlerUserName" width="100" />
        <!-- 可操作状态 -->
        <el-table-column label="任务状态" align="center" prop="status" width="120">
          <template #default="scope">
            <template v-if="scope.row.status == 6">
              <el-button type="info">{{ task_status.find((item) => item.value == scope.row.status)?.label }}</el-button>
            </template>
            <template v-else>
              <el-button type="success">{{ task_status.find((item) => item.value == scope.row.status)?.label }} </el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="当前审批人" align="center" prop="reviewerName" width="120" />
        <el-table-column label="当前审批状态" align="center" prop="reviewerStatus" width="120">
          <template #default="scope">
            <el-button v-if="scope.row.reviewerStatus !== null && scope.row.reviewerStatus !== undefined" type="danger">
              {{ review_status.find((item) => item.value === scope.row.reviewerStatus)?.label }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="异议状态" align="center" prop="objectionStatus" width="100">
          <template #default="scope">
            <template v-if="scope.row.objectionStatus == 1">
              <el-button type="danger">异议</el-button>
            </template>
            <template v-else-if="scope.row.objectionStatus == 2">
              <el-button type="success">正常</el-button>
            </template>
            <template v-else>
              {{ task_objection_status.find((item) => item.value == scope.row.objectionStatus)?.label }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="预计开始时间" align="center" prop="expectedStartTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预计结束时间" align="center" prop="expectedEndTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.expectedEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际开始时间" align="center" prop="actualStartTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="120">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" p>
          <template #default="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top-start">
              <p class="text-ellipsis whitespace-nowrap overflow-hidden">{{ scope.row.remark }}</p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template #default="scope">
            <!--            <el-button v-if="['2', '3', '4'].includes(scope.row.status)" link type="primary" size="small" icon="View" @click="handleView(scope.row)"-->
            <!--              >查看-->
            <!--            </el-button>-->
            <el-tooltip content="提交废弃审批" placement="top">
              <el-button v-if="!scope.row.reviewerStatus" v-hasPermi="['oa:task:discard']" type="danger" @click="handleDiscard(scope.row)">
                提交废弃审批
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Task" lang="ts">
import { pageSubTask, getTask, delTask, addTask, updateTask, turn, downLoadRestockingTemplate, discardTask } from '@/api/task/task';
import { TaskVO, TaskQuery, TaskForm, Collaborator } from '@/api/task/task/types';
import { listTaskType } from '@/api/task/taskType';
import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { task_status, user_type, review_status, task_objection_status } = toRefs<any>(
  proxy?.useDict('task_status', 'user_type', 'review_status', 'task_objection_status')
);
const route = useRoute();

const taskList = ref<TaskVO[]>([]);
const taskOptions = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);

const multiple = ref(true);
const total = ref(0);
const defaultMainTaskId = ref('');

const queryFormRef = ref<ElFormInstance>();
const isVisible = ref(false);

const initFormData: any = {
  taskId: undefined,
  taskName: undefined,
  taskTypeId: undefined,
  content: undefined,
  fileName: undefined,
  expectedStartTime: undefined,
  expectedEndTime: undefined,
  actualStartTime: undefined,
  actualEndTime: undefined,
  // score: undefined,
  // originalScore: undefined,
  handlerUserId: undefined,
  userType: undefined,
  status: undefined,
  remark: undefined,
  collaborators: []
};

const data = reactive<PageData<TaskForm, TaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: undefined,
    taskTypeId: undefined,
    content: undefined,
    expectedStartTime: undefined,
    expectedEndTime: undefined,
    actualStartTime: undefined,
    actualEndTime: undefined,
    // score: undefined,
    handlerUserId: undefined,
    userType: undefined,
    status: undefined,
    objectionStatus: undefined,
    params: {}
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询任务列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.mainTaskId = defaultMainTaskId.value;
  const res = await pageSubTask(queryParams.value);
  taskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询任务类型列表 */
const getTaskTypeList = async () => {
  loading.value = true;
  const res = await listTaskType();
  taskOptions.value = res.rows;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TaskVO[]) => {
  ids.value = selection.map((item) => item.taskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 提交废弃按钮操作 */
const handleDiscard = async (row?: TaskVO) => {
  loading.value = true;
  const _taskIds = row?.taskId || ids.value;
  await proxy?.$modal.confirm('是否确认提交废弃审批任务编号为"' + _taskIds + '"的数据项？').finally(() => (loading.value = false));
  await discardTask(_taskIds).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('成功');
  await getList();
};

/** 返回按钮操作 */
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/task/task'
  };
  proxy?.$tab.closeOpenPage(obj);
};

onMounted(() => {
  getTaskTypeList();
  defaultMainTaskId.value = route.params.mainTaskId as string;
  getList();
});
</script>
